package xyz.longicorn.driver.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.longicorn.driver.config.BizException;
import xyz.longicorn.driver.dao.FolderInfoMapper;
import xyz.longicorn.driver.dto.FileItem;
import xyz.longicorn.driver.pojo.FileInfo;
import xyz.longicorn.driver.pojo.FolderInfo;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class FolderService extends ServiceImpl<FolderInfoMapper, FolderInfo> {
    @Resource
    private FileService fileService;

    /**
     * 根据路径查询目录信息
     *
     * @param uid
     * @param path
     * @return
     */
    public FolderInfo getByPath(int uid, String path) {
        return this.getBaseMapper().getByPath(uid, path);
    }

    /**
     * 根据目录的名称查询信息
     *
     * @param uid
     * @param name
     * @param parentId
     * @return
     */
    public FolderInfo getByNameAndParent(int uid, String name, long parentId) {
        QueryWrapper q = new QueryWrapper();
        q.eq("uid", uid);
        q.eq("name", name);
        q.eq("parent_id", parentId);
        return this.getOne(q);
    }

    public List<FileItem> listFolder(int uid, String path) {
        long parentId = 0; // 默认查询根目录
        // 路径为空或者 / 表示根目录
        if (path != null && !path.equals("/")) {
            FolderInfo f = this.getByPath(uid, path); // 根据路径查询目录信息
            if (f == null) throw BizException.create("查询路径不存在"); // 没有查询到信息
            parentId = f.getId(); // 设置查询的父目录id
        }
        QueryWrapper q = new QueryWrapper();
        q.eq("parent_id", parentId); // 设置查询条件
        q.eq("uid", uid);
        // 查询目录集合
        final List<FolderInfo> folderList = this.list(q);
        List<FileItem> fsList = FileItem.buildFolderList(folderList); // 直接将folder集合转成fileitem集合

        final List<FileInfo> fileInfos = fileService.listByFolderId(uid, parentId);//文件信息
        fsList.addAll(FileItem.buildFileList(fileInfos)); // 合并目录和文件
        return fsList;
    }


    public FolderInfo create(int uid, String parent, String name) {
        long parentId = 0; // 默认根目录
        if (parent != null && !parent.equals("/")) {
            FolderInfo f = this.getByPath(uid, parent); // 根据路径查询目录信息
            if (f == null) throw BizException.create("父目录不存在"); // 没有查询到信息
            parentId = f.getId(); // 设置查询的父目录id
        }
        // 根据目录查询是否存在
        FolderInfo myFolderInfo = this.getByNameAndParent(uid, name, parentId);//根据名称查询目录信息
        if (myFolderInfo != null) {
            throw BizException.create("文件夹已经存在了");
        }
        FolderInfo fNew = new FolderInfo();
        fNew.setUid(uid);
        fNew.setName(name);
        fNew.setParentId(parentId);
        fNew.setPath((parent.equals("/") ? "" : parent) + "/" + name);
        return this.save(fNew) ? fNew : null;
    }
}
